<template>
  <div class="loan-report-container">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" ref="searchFormRef">
        <el-form-item label="统计周期" prop="period">
          <!-- 修改宽度 -->
          <el-select v-model="searchForm.period" placeholder="请选择统计周期" @change="handlePeriodChange" style="width: 200px;">
            <el-option label="本月" value="month" />
            <el-option label="本季度" value="quarter" />
            <el-option label="本年度" value="year" />
            <el-option label="自定义" value="custom" />
          </el-select>
        </el-form-item>
        <el-form-item label="日期范围" prop="dateRange" v-if="searchForm.period === 'custom'">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="产品类型" prop="productType">
          <!-- 修改宽度 -->
          <el-select v-model="searchForm.productType" placeholder="请选择产品类型" clearable style="width: 200px;">
            <el-option label="全部" value="" />
            <el-option label="个人贷款" value="personal" />
            <el-option label="企业贷款" value="business" />
            <el-option label="抵押贷款" value="mortgage" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
          <!-- <el-button type="success" @click="handleExport">导出报表</el-button> -->
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 统计卡片 -->
    <div class="stat-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-card-title">贷款总额</div>
            <div class="stat-card-value">{{ formatMoney(statistics.totalAmount) }}</div>
            <div class="stat-card-compare" :class="statistics.amountCompare > 0 ? 'up' : 'down'">
              较上期{{ statistics.amountCompare > 0 ? '增长' : '下降' }} {{ Math.abs(statistics.amountCompare) }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-card-title">贷款笔数</div>
            <div class="stat-card-value">{{ statistics.totalCount }}</div>
            <div class="stat-card-compare" :class="statistics.countCompare > 0 ? 'up' : 'down'">
              较上期{{ statistics.countCompare > 0 ? '增长' : '下降' }} {{ Math.abs(statistics.countCompare) }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-card-title">平均贷款金额</div>
            <div class="stat-card-value">{{ formatMoney(statistics.avgAmount) }}</div>
            <div class="stat-card-compare" :class="statistics.avgAmountCompare > 0 ? 'up' : 'down'">
              较上期{{ statistics.avgAmountCompare > 0 ? '增长' : '下降' }} {{ Math.abs(statistics.avgAmountCompare) }}%
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-card-title">平均贷款期限</div>
            <div class="stat-card-value">{{ statistics.avgTerm }}个月</div>
            <div class="stat-card-compare" :class="statistics.avgTermCompare > 0 ? 'up' : 'down'">
              较上期{{ statistics.avgTermCompare > 0 ? '增长' : '下降' }} {{ Math.abs(statistics.avgTermCompare) }}%
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 图表区域 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">贷款金额趋势</div>
          <div ref="amountChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">贷款笔数趋势</div>
          <div ref="countChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">产品类型分布</div>
          <div ref="productChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <div class="chart-title">贷款期限分布</div>
          <div ref="termChartRef" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 数据表格 -->
    <el-card class="table-card">
      <div class="table-title">贷款数据明细</div>
      <el-table :data="tableData" border stripe>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="date" label="日期" width="100" align="center" />
        <el-table-column prop="productType" label="产品类型" width="120">
          <template #default="{ row }">
            {{ getProductTypeName(row.productType) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="贷款笔数" width="100" align="center" />
        <el-table-column prop="amount" label="贷款金额" width="150" align="right">
          <template #default="{ row }">
            {{ formatMoney(row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="avgAmount" label="平均金额" width="150" align="right">
          <template #default="{ row }">
            {{ formatMoney(row.avgAmount) }}
          </template>
        </el-table-column>
        <el-table-column prop="avgTerm" label="平均期限" width="100" align="center">
          <template #default="{ row }">
            {{ row.avgTerm }}个月
          </template>
        </el-table-column>
        <el-table-column prop="approvalRate" label="审批通过率" width="120" align="center">
          <template #default="{ row }">
            {{ row.approvalRate }}%
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="page.current"
          v-model:page-size="page.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="page.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// 搜索表单
const searchForm = reactive({
  period: 'month',
  dateRange: [],
  productType: ''
})

// 统计数据
const statistics = reactive({
  totalAmount: 5680000,
  amountCompare: 12.5,
  totalCount: 86,
  countCompare: 8.2,
  avgAmount: 66046.51,
  avgAmountCompare: 4.3,
  avgTerm: 18.5,
  avgTermCompare: -2.1
})

// 表格数据
const tableData = ref([
  {
    date: '2024-05-01',
    productType: 'personal',
    count: 12,
    amount: 720000,
    avgAmount: 60000,
    avgTerm: 12,
    approvalRate: 85.7
  },
  {
    date: '2024-05-02',
    productType: 'business',
    count: 8,
    amount: 1600000,
    avgAmount: 200000,
    avgTerm: 24,
    approvalRate: 72.3
  },
  {
    date: '2024-05-03',
    productType: 'mortgage',
    count: 5,
    amount: 2500000,
    avgAmount: 500000,
    avgTerm: 36,
    approvalRate: 90.2
  },
  {
    date: '2024-05-04',
    productType: 'personal',
    count: 15,
    amount: 860000,
    avgAmount: 57333.33,
    avgTerm: 12,
    approvalRate: 88.5
  }
])

// 分页
const page = reactive({
  current: 1,
  size: 10,
  total: 4
})

// 图表引用
const amountChartRef = ref(null)
const countChartRef = ref(null)
const productChartRef = ref(null)
const termChartRef = ref(null)

// 初始化图表
onMounted(() => {
  initAmountChart()
  initCountChart()
  initProductChart()
  initTermChart()
})

// 初始化贷款金额趋势图
const initAmountChart = () => {
  const chart = echarts.init(amountChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />{a}: {c}万元'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '金额（万元）'
    },
    series: [
      {
        name: '贷款金额',
        type: 'line',
        data: [320, 420, 380, 520, 568, 610, 580, 650, 720, 680, 750, 820],
        smooth: true,
        lineStyle: {
          width: 3,
          color: '#409EFF'
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: 'rgba(64, 158, 255, 0.5)' },
              { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
            ]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化贷款笔数趋势图
const initCountChart = () => {
  const chart = echarts.init(countChartRef.value)
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: '{b}<br />{a}: {c}笔'
    },
    xAxis: {
      type: 'category',
      data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
    },
    yAxis: {
      type: 'value',
      name: '笔数'
    },
    series: [
      {
        name: '贷款笔数',
        type: 'bar',
        data: [45, 52, 48, 65, 86, 95, 88, 102, 110, 105, 115, 125],
        itemStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              { offset: 0, color: '#67C23A' },
              { offset: 1, color: '#95D475' }
            ]
          }
        }
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化产品类型分布图
const initProductChart = () => {
  const chart = echarts.init(productChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}笔 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['个人贷款', '企业贷款', '抵押贷款']
    },
    series: [
      {
        name: '产品类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 16,
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 45, name: '个人贷款' },
          { value: 25, name: '企业贷款' },
          { value: 16, name: '抵押贷款' }
        ]
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 初始化贷款期限分布图
const initTermChart = () => {
  const chart = echarts.init(termChartRef.value)
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c}笔 ({d}%)'
    },
    legend: {
      orient: 'vertical',
      right: 10,
      top: 'center',
      data: ['3个月', '6个月', '12个月', '24个月', '36个月']
    },
    series: [
      {
        name: '贷款期限',
        type: 'pie',
        radius: '70%',
        data: [
          { value: 10, name: '3个月' },
          { value: 15, name: '6个月' },
          { value: 30, name: '12个月' },
          { value: 20, name: '24个月' },
          { value: 11, name: '36个月' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  chart.setOption(option)
  window.addEventListener('resize', () => {
    chart.resize()
  })
}

// 周期变更
const handlePeriodChange = (val) => {
  if (val !== 'custom') {
    searchForm.dateRange = []
  }
}

// 搜索
const handleSearch = () => {
  // TODO: 调用搜索接口
  console.log('搜索条件:', searchForm)
}

// 重置
const handleReset = () => {
  searchForm.period = 'month'
  searchForm.dateRange = []
  searchForm.productType = ''
  handleSearch()
}

// 导出报表
const handleExport = () => {
  ElMessage.success('报表导出成功')
}

// 分页
const handleSizeChange = (val) => {
  page.size = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  page.current = val
  handleSearch()
}

// 格式化金额
const formatMoney = (value) => {
  if (!value) return '0元'
  return value.toLocaleString() + '元'
}

// 获取产品类型名称
const getProductTypeName = (type) => {
  const typeMap = {
    personal: '个人贷款',
    business: '企业贷款',
    mortgage: '抵押贷款'
  }
  return typeMap[type] || '未知类型'
}
</script>

<style scoped>
.loan-report-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  height: 120px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stat-card-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.stat-card-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 10px;
}

.stat-card-compare {
  font-size: 12px;
}

.stat-card-compare.up {
  color: #67C23A;
}

.stat-card-compare.down {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 400px;
}

.chart-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.chart-container {
  height: 320px;
}

.table-card {
  margin-bottom: 20px;
}

.table-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 20px;
  padding-left: 10px;
  border-left: 3px solid #409EFF;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>